//
//  CLOPlayer.swift
//  CLOCamera_Example
//
//  Created by Clover on 2018/5/17.
//  Copyright © 2018年 CocoaPods. All rights reserved.
//

import UIKit
import AVFoundation
public class CLOPlayer: UIView {
    private var _videoUrl: URL?
    var videoUrl: URL?{
        set{
            _videoUrl = newValue
        }get{
            return _videoUrl
        }
    }
    lazy var player: AVPlayer? = {
        let temp = AVPlayer.init(playerItem: getAVPlayerItem())
        return temp
    }()
    
    //MARK: - life
    deinit {
        removeAvPlayerNoti()
        stopPlayer()
        player = nil
    }

    public convenience init(frame: CGRect, bgView: UIView, url: URL){
        self.init(frame: frame)
        _videoUrl = url
        let _ = self.player
        addAVPlayerNoti(item: (self.player?.currentItem)!)
        
        self.videoUrl = url
        let playerLayer = AVPlayerLayer.init(player: player)
        playerLayer.frame = self.bounds
        self.layer.addSublayer(playerLayer)
        bgView.addSubview(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required public init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    }
    
    //MARK: - public
    public func starPlay(){
        removeAvPlayerNoti()
        nextPlayer()
    }
    
    //MARK: - private methods
    public func stopPlayer(){
        if (self.player?.rate == 1) {
            self.player?.pause()
        }
    }
    
    private func getAVPlayerItem() -> AVPlayerItem{
        let playerItem = AVPlayerItem.init(url: _videoUrl!)
        return playerItem
    }
    
    private func nextPlayer(){//
//        let second = (player?.currentItem?.duration.timescale)! != 0 ? : 10
//        self.player?.seek(to: CMTimeMakeWithSeconds(0, second))
        player?.replaceCurrentItem(with: getAVPlayerItem())
        addAVPlayerNoti(item: (player?.currentItem)!)
        if player?.rate == 0 {
            player?.play()
        }
    }
   
    @objc private func playbackFinished(noti: NSNotification){
        player?.seek(to: CMTime.init(value: 0, timescale: 1))
        player?.play()
    }
    //MARK: - noti
    private func addAVPlayerNoti(item: AVPlayerItem){
        item.addObserver(self, forKeyPath: "status", options: .new, context: nil)
        item.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(playbackFinished(noti:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
    }
    
    private func removeAvPlayerNoti(){
        let palyerItem = player?.currentItem
        palyerItem?.removeObserver(self, forKeyPath: "status")
        palyerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
        NotificationCenter.default.removeObserver(self)
    }
    
    override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let playerItem: AVPlayerItem = object as! AVPlayerItem
        if keyPath == "status"{
            let status: AVPlayerStatus = AVPlayerStatus(rawValue:(change![NSKeyValueChangeKey.newKey] as! Int))!
            if status == .readyToPlay{
//                print("正在播放...，视频总长度\(CMTimeGetSeconds(playerItem.duration))")
            }
        }else if(keyPath == "loadedTimeRanges"){
            let array = playerItem.loadedTimeRanges
            // 本次缓冲时间范围
            let timeRange: CMTimeRange = (array.first?.timeRangeValue)!
            let startSeconds: Float = Float(CMTimeGetSeconds(timeRange.start))
            let durationSeconds: Float = Float(CMTimeGetSeconds(timeRange.duration))
            let totalBuffer: TimeInterval = TimeInterval(startSeconds + durationSeconds)
//            print("共缓冲：\(totalBuffer)")
        }
    }
}
